package com.ueit.vote.controller;

import cn.hutool.core.date.DateTime;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.BaseException;
import com.ruoyi.common.core.exception.PreAuthorizeException;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import com.ueit.vote.domain.UeweixinVote;
import com.ueit.vote.domain.UeweixinVoteItem;
import com.ueit.vote.domain.UeweixinVoteRecord;
import com.ueit.vote.service.IUeweixinVoteItemService;
import com.ueit.vote.service.IUeweixinVoteRecordService;
import com.ueit.vote.service.IUeweixinVoteService;
import com.ueit.vote.vo.FrontVoteData;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

@Slf4j
@RestController
@RequestMapping("/voteFront")
public class VoteFrontController extends BaseController {


    /****************前端接口**************************/

    @Autowired
    private IUeweixinVoteService ueweixinVoteService;
    @Autowired
    private IUeweixinVoteItemService ueweixinVoteItemService;
    @Autowired
    private IUeweixinVoteRecordService ueweixinVoteRecordService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private  WxMpService wxMpService;

    /**
     * 获取活动首页信息
     */
    @GetMapping("/frontIndex/{voteId}")
    public AjaxResult frontIndex(@PathVariable("voteId")String voteId){
        //获取活动状态
//        UeweixinVote vote = redisService.getCacheObject("vote:id="+voteId);
//        if(StringUtils.isNull(vote)){
//             vote = ueweixinVoteService.selectUeweixinVoteById(voteId);
//            redisService.setCacheObject("vote:id="+voteId,vote);
//        }
        UeweixinVote vote = ueweixinVoteService.selectUeweixinVoteByToken(voteId);
        if(vote.getStatus().equals("1")){
            return AjaxResult.error();
        }
        UeweixinVoteItem query = new UeweixinVoteItem();
        query.setVoteToken(voteId);
        List<UeweixinVoteItem> itemList = ueweixinVoteItemService.selectUeweixinVoteItemListFront(query);
        Map<String,Object> mmap = new HashMap<>();
        mmap.put("vote",vote);
        mmap.put("itemList",itemList);
        return AjaxResult.success(mmap);
    }
    @GetMapping("/frontServerTime/{voteId}")
    public AjaxResult serverTime(@PathVariable("voteId")String voteId){
        //获取活动剩余时间
        UeweixinVote vote = ueweixinVoteService.selectUeweixinVoteByToken(voteId);
                Long nowTime = DateTime.now().getTime();
                Long overTime = vote.getEnddate().getTime();
                Long startTime = vote.getStatdate().getTime();
                Map<String,Object> mmap = new HashMap<>();
                if(nowTime <= startTime){
                    mmap.put("result",-1);
                    mmap.put("number",startTime-nowTime);
                }
                if(nowTime>startTime&& nowTime<overTime){
                    mmap.put("result",1);
                    mmap.put("number",overTime-nowTime);
                }
                if(nowTime>overTime){
                    mmap.put("result",2);
                    mmap.put("number",0);
                }
        return AjaxResult.success(mmap);
    }

    /**
     * 获取活动选项详细内容
     * @param itemId
     * @return
     */
    @GetMapping("/frontGetItemDetails/{itemId}")
    public AjaxResult getItemDetails(@PathVariable("itemId") Long itemId){

        return AjaxResult.success(ueweixinVoteItemService.selectUeweixinVoteItemById(itemId));
    }

    /**
     * 投票功能
     */
    @PostMapping("/voteByUser")
    public AjaxResult vote(@RequestBody FrontVoteData frontVoteData){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

        //判断限制每天投票数限制每个用户每个活动每天的投票数，超过不让投票,0表示不限制,默认为0,请输入整数
        UeweixinVote vote = ueweixinVoteService.selectUeweixinVoteByToken(frontVoteData.getVoteId());

        //今天0点时间戳
        long current=System.currentTimeMillis();//当前时间毫秒数
        long zero=current/(1000*3600*24)*(1000*3600*24)- TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
        long twelve=zero+24*60*60*1000-1;//今天23点59分59秒的毫秒数
        Long overTime = vote.getEnddate().getTime();
        Long startTime = vote.getStatdate().getTime();
        Map<String,Object> result1 = new HashMap<>();//返回结果，根据此结果展示不同的提示信息
        if(current < startTime){
            result1.put("rescode",1);
            result1.put("message","投票活动还未开始");
            return AjaxResult.success(result1);
        }
        if(current > overTime){
            result1.put("rescode",1);
            result1.put("message","投票活动已结束");
            return AjaxResult.success(result1);
        }

        if(vote.getStatus().equals("0")&&vote.getDayLimitNum()>0){
            //getDayLimitNum ==0则不限制，否则判断当前用户当天已投票次数
            UeweixinVoteRecord query = new UeweixinVoteRecord();
            query.setVoteToken(frontVoteData.getVoteId());
            query.setAccountId(loginUser.getAccountId());
            query.setStartTime(zero);
            query.setEndTime(twelve);
            int result = ueweixinVoteRecordService.CountRecord(query);

            if(result >= vote.getDayLimitNum()){
                result1.put("rescode",1);
                result1.put("message","今日投票次数已达上限，请明天再来");
                return AjaxResult.success(result1);
            }
        }
        //请输入限制每个用户每个活动总的投票数，超过不让投票,0表示不限制,默认为0,请输入整数
        if(vote.getStatus().equals("0")&&vote.getAllLimitNum()>0){
            //大于0表示限制活动中总投票数
            UeweixinVoteRecord query = new UeweixinVoteRecord();
            query.setVoteToken(frontVoteData.getVoteId());
            int result = ueweixinVoteRecordService.CountRecord(query);
            if(result >= vote.getAllLimitNum()){
                result1.put("rescode",1);
                result1.put("message","本次活动您已投票至上限");
                return AjaxResult.success(result1);
            }
        }
        //限制每个选项每天获得的票数,0表示不限制,1表示每个用户每天只能给该选项投1票,默认为0,请输入整数
        if(vote.getStatus().equals("0")&&vote.getSelecterLimitNum()>0){
            //为0则不限制
            UeweixinVoteRecord query = new UeweixinVoteRecord();
            query.setVoteToken(frontVoteData.getVoteId());
            query.setVoteItemId(frontVoteData.getItemId());
            query.setAccountId(loginUser.getAccountId());

            query.setStartTime(zero);
            query.setEndTime(twelve);
            int result = ueweixinVoteRecordService.CountRecord(query);
            if(result >= vote.getSelecterLimitNum()){
                result1.put("rescode",1);
                result1.put("message","今天您已为此用户投票达到上限");
                return AjaxResult.success(result1);
            }
        }
        UeweixinVoteRecord record = new UeweixinVoteRecord();
        record.setAccountId(loginUser.getAccountId());
        record.setVoteToken(frontVoteData.getVoteId());
        record.setVoteItemId(frontVoteData.getItemId());
        record.setVoteTime(DateTime.now().getTime());
        record.setVoteIp( IpUtils.getIpAddr(ServletUtils.getRequest()));
        record.setVoteTouched(1L);
        if(ueweixinVoteRecordService.insertUeweixinVoteRecord(record)>0){
            UeweixinVoteItem entity = ueweixinVoteItemService.selectUeweixinVoteItemById(frontVoteData.getItemId());
            entity.setVoteItemCount(entity.getVoteItemCount()+1);
            ueweixinVoteItemService.updateUeweixinVoteItem(entity);
            log.info("参赛人员{},当前票数为{}",entity.getVoteItemTitle(),entity.getVoteItemCount());
            log.info("用户{}投票成功，ip地址为:{},数量{}",loginUser.getThirdAuthUser().getUmsAccountInfo().getNickname(),IpUtils.getIpAddr(ServletUtils.getRequest()),record.getVoteTouched());
        }
        else{
            log.error("投票失败，系统出错");
            throw new BaseException("系统出错，投票失败");
        }
        result1.put("rescode",0);
        result1.put("message","投票成功");
        return AjaxResult.success(result1);
    }

    /**
     * 获取排行榜信息
     */
    @GetMapping("/frontRankingList/{voteId}")
    public AjaxResult rankingList(@PathVariable("voteId")String voteId){
        UeweixinVoteItem query = new UeweixinVoteItem();
        query.setVoteToken(voteId);
        query.setOrderByCount(1);
        List<UeweixinVoteItem> list = ueweixinVoteItemService.selectUeweixinVoteItemListFront(query);
        return AjaxResult.success(list);
    }

    /**
     * 获取微信jsapi数据
     */
    @GetMapping("/frontGetTicket")
    public AjaxResult frontGetTicket(@RequestParam("url")String url){
        try {
          WxJsapiSignature ticket =  wxMpService.createJsapiSignature(url);
          return AjaxResult.success(ticket);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }
    /**
     * 判断当前用户是否能投票
     */
    @PostMapping("/frontRankingCheck")
    public AjaxResult checkVote(@RequestBody FrontVoteData frontVoteData){
        log.info("fromtData:{}",frontVoteData.getVoteId(),frontVoteData.getItemId());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if(StringUtils.isNull(loginUser)){
            log.error("当前登录用户为空");
           return new AjaxResult(HttpStatus.UNAUTHORIZED,"用户登录已失效");
        }
        //判断限制每天投票数限制每个用户每个活动每天的投票数，超过不让投票,0表示不限制,默认为0,请输入整数
        UeweixinVote vote = ueweixinVoteService.selectUeweixinVoteByToken(frontVoteData.getVoteId());
        String openId = loginUser.getThirdAuthUser().getUmsAccountAuth().getIdentifier();
        //今天0点时间戳
        long current=System.currentTimeMillis();//当前时间毫秒数
        long zero=current/(1000*3600*24)*(1000*3600*24)- TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
        long twelve=zero+24*60*60*1000-1;//今天23点59分59秒的毫秒数
        Map<String,Object> result1 = new HashMap<>();//返回结果，根据此结果展示不同的提示信息
        //判断此活动是否需要先关注公众号
        if(StringUtils.equals(UserConstants.YES,vote.getSubscribe())){
            log.info("需要关注公众号后才能投票,当前openid为{}"+openId);
            //判断是否关注公众号
            try {
                log.info("当前公众号id为{}",wxMpService.getWxMpConfigStorage());
                WxMpUser wxMpUser =  wxMpService.getUserService().userInfo(openId,"zh_CN");
                log.info("获取到的微信用户信息为:{}",wxMpUser.toString());
                if(!wxMpUser.getSubscribe()){
                    result1.put("rescode",2);
                    result1.put("message","请先关注公众号后进行投票");
                    log.info("用户{},openid={}关注公众号状态为:{}",loginUser.getThirdAuthUser().getUmsAccountInfo().getNickname(),wxMpUser.getOpenId(),wxMpUser.getSubscribe());
                    return AjaxResult.success(result1);
                }
            } catch (WxErrorException e) {
                log.error("报错信息{}",e.getMessage());
                e.printStackTrace();
            }
        }
        if(vote.getStatus().equals("0")&&vote.getDayLimitNum()>0){
            //getDayLimitNum ==0则不限制，否则判断当前用户当天已投票次数
            UeweixinVoteRecord query = new UeweixinVoteRecord();
            query.setVoteToken(frontVoteData.getVoteId());
            query.setAccountId(loginUser.getAccountId());
            query.setStartTime(zero);
            query.setEndTime(twelve);
            int result = ueweixinVoteRecordService.CountRecord(query);
            if(result >= vote.getDayLimitNum()){
                log.info("用户{}当天投票次数已用尽",loginUser.getThirdAuthUser().getUmsAccountInfo().getNickname());
                result1.put("rescode",1);
                result1.put("message","今日投票次数已达上限，请明天再来");
                return AjaxResult.success(result1);
            }
        }
        //请输入限制每个用户每个活动总的投票数，超过不让投票,0表示不限制,默认为0,请输入整数
        if(vote.getStatus().equals("0")&&vote.getAllLimitNum()>0){
            //大于0表示限制活动中总投票数
            UeweixinVoteRecord query = new UeweixinVoteRecord();
            query.setVoteToken(frontVoteData.getVoteId());
            int result = ueweixinVoteRecordService.CountRecord(query);
            if(result >= vote.getAllLimitNum()){
                log.info("用户{}本次活动投票次数已用尽",loginUser.getThirdAuthUser().getUmsAccountInfo().getNickname());
                result1.put("rescode",1);
                result1.put("message","本次活动您已投票至上限");
                return AjaxResult.success(result1);
            }
        }
        //限制每个选项每天获得的票数,0表示不限制,1表示每个用户每天只能给该选项投1票,默认为0,请输入整数
        if(vote.getStatus().equals("0")&&vote.getSelecterLimitNum()>0){
            //为0则不限制
            UeweixinVoteRecord query = new UeweixinVoteRecord();
            query.setVoteToken(frontVoteData.getVoteId());
            query.setVoteItemId(frontVoteData.getItemId());
            query.setAccountId(loginUser.getAccountId());
            query.setStartTime(zero);
            query.setEndTime(twelve);
            int result = ueweixinVoteRecordService.CountRecord(query);
            if(result >= vote.getSelecterLimitNum()){
                log.info("用户{}给选项{}当天投票次数已用尽",loginUser.getThirdAuthUser().getUmsAccountInfo().getNickname(),frontVoteData.getItemId());
                result1.put("rescode",1);
                result1.put("message","今天您已为此用户投票达到上限");
                return AjaxResult.success(result1);
            }
        }
        result1.put("rescode",0);
        result1.put("message","可投票");
        return AjaxResult.success(result1);

    }

}
